<template>
    <div v-loading="loading">
        <!-- 过滤条件 -->
        <div class="filter flex flex-between flex-y">
            <div class="flex">
                <el-input
                    v-model="query.searchStr"
                    style="width:200px;"
                    class="right20"
                    placeholder="请输入关键字"
                    prefix-icon="el-icon-search"
                    @input.native="Revise"
                    @keyup.enter.native="Query()"
                />
                <div class="flex flex-y right20">
                    <div class="right10">推荐位置</div>
                    <el-select
                        v-model="query.recommendLocation"
                        style="width:140px"
                        clearable
                        placeholder="全部"
                        @change="Query()"
                    >
                        <el-option
                            v-for="(val,name) in recommendList"
                            :key="name"
                            :label="name"
                            :value="val"
                        />
                    </el-select>
                </div>
                <div class="flex flex-y right20">
                    <div class="right10">置顶位置</div>
                    <el-select
                        v-model="query.top"
                        style="width:140px"
                        clearable
                        placeholder="全部"
                        @change="Query()"
                    >
                        <el-option
                            v-for="(val,name) in topList"
                            :key="name"
                            :label="name"
                            :value="val"
                        />
                    </el-select>
                </div>
                <div class="flex flex-y right20">
                    <div class="right10">账号类型</div>
                    <el-select
                        v-model="query.accountType"
                        clearable
                        style="width:140px"
                        placeholder="全部"
                        @change="Query()"
                    >
                        <el-option
                            v-for="(item,index) in typeList"
                            :key="item"
                            :label="item"
                            :value="index"
                        />
                    </el-select>
                </div>
                <div class="flex flex-y right20">
                    <div class="right10">用户类型</div>
                    <el-select
                        v-model="query.userType"
                        clearable
                        style="width:140px"
                        placeholder="全部"
                        @change="Query()"
                    >
                        <el-option
                            v-for="(item, index) in userType"
                            :key="item"
                            :label="item"
                            :value="index + 1"
                        />
                    </el-select>
                </div>
                <div class="flex flex-y right20">
                    <div class="right10">推荐日期</div>
                    <el-date-picker
                        v-model="date"
                        style="width:220px"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        @change="Query()"
                    />
                </div>
            </div>
            <el-button type="primary" @click="Export">导出全部</el-button>
            <el-button type="danger" @click="Remove()">批量移出</el-button>
        </div>

        <!-- 表格 -->
        <div class="main">
            <el-table
                ref="table"
                fit
                :data="tableData"
                style="width: 100%"
                @sort-change="Orderby"
            >
                <el-table-column type="selection" xin-width="250" />
                <el-table-column type="index" label="排序" width="50" />
                <el-table-column
                    v-for="key in headFilter"
                    :key="key"
                    :prop="header[key]"
                    :label="key"
                    :sortable="/推荐时间|热度|被点赞|被收藏|被评论|被转发|不感兴趣|收益|悬赏/.test(key)?'custom':false"
                    :formatter="Formatter"
                />
                <el-table-column fixed="right" width="210px" label="操作" align="right">
                    <template #header>
                        <span style="margin-right: 1rem">操作</span>
                        <el-popover trigger="hover">
                            <el-checkbox-group v-model="headFilter" @change="Sort">
                                <div
                                    v-for="key in Object.keys(header).sort((a,b)=>a.localeCompare(b))"
                                    :key="key"
                                    style="padding:0.5rem"
                                >
                                    <el-checkbox :label="key">{{ key }}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                            <template slot="reference">
                                <el-button size="mini" icon="el-icon-menu">表头过滤</el-button>
                            </template>
                        </el-popover>
                    </template>
                    <template #default="{row}">
                        <!-- <el-button type="text" @click.native="View('view',row)">查看</el-button> -->
                        <el-button type="text" size="small" @click="Top(row)">{{ (row.top?'取消':'' )+'置顶' }}</el-button>
                        <el-button v-if="row.top" type="text" size="small" @click="Move('1',row)">上移</el-button>
                        <el-button v-if="row.top" type="text" size="small" @click="Move('0',row)">下移</el-button>
                        <el-button type="text" size="small" @click="Remove(row)">移出</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <page :total="total" @change="Query" />
        </div>
    </div>
</template>

<script>
import { formatDate } from 'kfz-utils/lib/date.js'
import msgRadio from '../components/msgRadio'
import page from '@/components/public/Pagination'
import { remote } from '@/api/index'
/*
    [排序, 用户类型, 帐号名称, 账号类型, 用户ID, 推荐时间, 会员类型, 账号状态, 被点赞, 被收藏, 被评论, 被转发, 被不感兴趣, 热度, 收益, 悬赏, 当前状态, 操作]
    [排序, 用户类型, 账号名称, 账号类型, 作者ID, 内容ID, 发布时间, 话题,                                      热度, 收益, 悬赏, 当前状态, 操作]
*/
const mix = {
    用户类型: 'userType',
    账号名称: 'realName',
    账号类型: 'accountType',
    用户ID: 'id',
    热度: 'heat',
    收益: 'earnings',
    悬赏: 'reward',
    当前状态: 'top'
}
const _header = type =>
    type === 'userRecommend'
        ? {
            ...mix,
            推荐时间: 'recommendDate',
            会员类型: 'vipType',
            账号状态: 'accountStatus',
            被点赞: 'supports',
            被收藏: 'collects',
            被评论: 'commons',
            被转发: 'forwards',
            被不感兴趣: 'uninterested',
            推荐位置: 'recommendLocation'
        }
        : {
            ...mix,
            内容ID: 'contentId',
            发布时间: 'releaseDate',
            话题: 'topic'
        }
function initHeader (layout) {
    const header = Object.keys(_header(layout)).sort((a, b) => a.localeCompare(b))
    const saveHeader = window.localStorage[layout + 'Header']
    return saveHeader ? header.filter(x => JSON.parse(saveHeader).includes(x)) : header
}

export default {
    // eslint-disable-next-line vue/no-unused-components
    components: { page, msgRadio },
    props: {
        layout: { default: 'user' }
    },
    data () {
        return {
            loading: false,
            tableData: [],
            header: _header(this.layout),
            // 表头过滤器
            headFilter: initHeader(this.layout),
            recommendList: {
                '人脉+关注': '3',
                关注: '0',
                人脉: '1'
            },
            topList: {
                '人脉+关注': '1',
                关注: '2',
                人脉: '3'
            },
            typeList: ['砂锅用户', '砂锅号用户'],
            userType: ['投资人', '服务商', '创业者', '上班族', '在校生', '未认证砂锅用户', '个人', '政府', '媒体', '企业', '未认证砂锅号用户'],
            date: [],
            query: {
                // 用户类型，传完整值（创业者、投资人、服务商、上班族、在校生、个人、媒体、政府、企业）
                userType: null,
                // 账号类型，传完整值（砂锅号用户、砂锅用户）
                accountType: null,
                // 查询词
                searchStr: null,
                // 推荐位置，传数字（1：首页，2：热搜）
                recommendLocation: null,
                // 排序
                orderBy: null,
                pageNum: 1,
                pageSize: 20,
                top: ''
            },
            total: 0,
            oo: '6'
        }
    },
    computed: {},
    watch: {},
    created () {
        this.Query()
    },
    methods: {
        Query ({ pageSize, pageNum = 1 } = {}) {
            this.date = this.date || []
            this.query = {
                ...this.query,
                ...{
                    beginTime: this.date[0] || null,
                    endTime: this.date[1] || null,
                    pageSize: pageSize || this.query.pageSize,
                    pageNum
                }
            }
            for (const key in this.query) {
                const _val = this.query[key]
                this.query[key] = _val === '' || _val === undefined ? null : _val
            }
            // console.log(this.query)
            if (this.loading) {
                return false
            }
            this.loading = true
            HTTP('userRecommendList', this.query).then(
                ({ rows = [], total }) => {
                    console.log(total, rows)
                    this.total = total
                    this.tableData = rows
                }
            ).finally(_ => (this.loading = false))
        },
        View (type, row) {

        },
        Move (topOrBottom, { accountType, uid } = {}) {
            if (!(accountType || uid || topOrBottom)) return false
            HTTP(this.layout + 'Move', { topOrBottom, accountType, uid }).then(_ => {
                this.$message.success('操作完成')
                this.Query()
            })
        },
        async $Radio ({ list = {}, initValue = '', title = '' }) {
            let result = ''
            await this.$msgbox({
                title: title,
                center: true,
                showCancelButton: true,
                message: (<msg-radio initValue={initValue} item={list}/>),
                beforeClose (action, instance, done) {
                    const _result = instance.$children[2].radio
                    // console.log('啊啊啊啊啊啊', action, instance, instance.$children[2].radio)
                    if (action === 'confirm') result = _result
                    done()
                }
            })
            return result
        },
        async Top ({ uid, top, accountType }) {
            console.log(top)
            const flag = +top
            const data = {
                uid,
                accountType
            }
            let title = ''
            let param = ''
            let list = {}
            // +top == false表示未置顶
            if (flag) {
                list = { 取消全部置顶: '1', 取消关注置顶: '2', 取消人脉置顶: '3' }
                title = '取消置顶'
                data.top = '0'
                param = 'cancelTop'
            } else {
                list = { 全部置顶: '1', 置顶关注: '2', 置顶人脉: '3' }
                title = '置顶'
                param = 'top'
            }
            const result = await this.$Radio({ list, initValue: top, title })
            data[param] = result
            console.log('操作项:', data)
            HTTP(this.layout + 'Top', data).then(_ => this.Query())
        },
        async Remove ({ uid } = {}) {
            const uids = uid || this.$refs.table.selection.map(v => v.uid).join(',')
            // console.log(uids)
            if (!uids.length) {
                return this.$message.warning('未选择移出项')
            }
            let result = '0'
            if (1) {
                // 批量移出
                await this.$confirm('确认移出选中项?', '提示', {
                    type: 'warning'
                })
            } else {
                // 单个移出
                result = await this.$Radio({ list: { 取消全部推荐: '1', 取消关注推荐: '2', 取消人脉推荐: '3' }, title: '取消推荐' })
            }
            console.log({ uids })

            await HTTP(this.layout + 'Remove', { uids })
            this.$refs.table.selection = 0
            this.$message.success('移出成功')
            this.Query()
        },
        async Export () {
            await this.$confirm('将导出当前条件下全部内容,请注意自行过滤', '提示', {
                type: 'warning'
            })
            // 差集
            const { pageSize, pageNum, ..._param } = this.query
            // console.log(_param)
            const { data: { msg: name } = {} } = await HTTP(this.layout + 'Export', _param)
            window.open(remote + 'common/download?fileName=' + name + '&delete=true')
        },
        Orderby ({ column: { label }, prop, order } = {}) {
            // 列表排序（发布时间的倒序：releaseDate DESC，升序：releaseDate ASC；热度的倒序：heat DESC，升序：heat ASC；收益的倒序：income DESC，升序：income ASC；悬赏的倒序：reward DESC，升序：reward ASC；）
            console.log(label)
            if (order) {
                this.query.orderBy = ['', '推荐时间', '热度', '被点赞', '被收藏', '被评论', '被转发', '不感兴趣', '收益', '悬赏'].indexOf(label)
                this.query.ascDesc = order.replace('ending', '')
            } else {
                this.query.orderBy = ''
                this.query.ascDesc = ''
            }
            this.query.pageNum = 1
            console.log(order, this.query)
            this.Query()
        },
        Sort (val) {
            console.log(val)

            this.headFilter = val.sort((a, b) => a.localeCompare(b))
            // console.log(val)

            if (val.length) {
                window.localStorage[this.layout + 'Header'] = JSON.stringify(val)
            } else {
                window.localStorage.removeItem(this.layout + 'Header')
            }
        },
        Revise ({ target: { value } }) {
            // 不能过滤特殊字符....有人昵称是emoji
            // const _val = value.replace(/[^A-Za-z0-9\u4E00-\u9FA5]/g, '')
            // value = _val
            const _val = value.trim()
            this.query.searchStr = _val === '' ? null : _val
            // console.log(this.query.searchStr)
        },
        Formatter (row, { label }, cellValue) {
            let _time
            switch (label) {
            case '账号类型':
                return +cellValue ? '砂锅号用户' : '砂锅用户'
            case '用户类型':
                return this.userType[cellValue]
            case '账号状态':
                return [
                    '未认证', '已认证', '审核中', '审核未通过', '正常', '冻结', '注销', '白名单', '灰名单', '黑名单', '封禁'
                ][cellValue]
            case '推荐时间':
                _time = cellValue * 1e3 || ''
                return _time ? formatDate(new Date(_time), 'yyyy-MM-dd hh:mm:ss') : '-'
            case '推荐位置':
                return isNaN(cellValue) ? '人脉+关注' : +cellValue ? '人脉' : '关注'
            case '当前状态':
                return (<p style="color:#0059B1">{['', '关注+人脉', '关注', '人脉'][cellValue]}</p>)
            default:
                return cellValue || '-'
            }

            // formatDate
        }
    }
}
</script>

<style lang="stylus" scoped>
.el-table--scrollable-x .el-table__body-wrapper
    overflow scroll !important
    height 29rem !important

.filter.flex.flex-between.flex-y
    >>> > .flex
        flex-wrap wrap
        &>div
            margin 10px
    ::v-deep .right10
        white-space nowrap
    ::v-deep .el-select
        width 88px !important

.filter
    padding 5px 30px 25px 40px
    background-color #fff
.main
    background-color #fff
    margin-top 10px
    padding 30px 50px
</style>
